'use client';

import React, { useState } from 'react';
import { Card, Button, List, message, Space, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';

export default function BatchGenerateLicense() {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [generating, setGenerating] = useState(false);

  const handleFileSelect = ({ fileList }: { fileList: UploadFile[] }) => {
    // 只允许JSON文件
    const jsonFiles = fileList.filter(file => {
      if (file.originFileObj) {
        const fileType = file.originFileObj.type;
        const fileName = file.name.toLowerCase();
        return fileType === 'application/json' || fileName.endsWith('.json');
      }
      return file.name.toLowerCase().endsWith('.json');
    });
    
    setFileList(jsonFiles);
  };

  const handleBatchGenerate = async () => {
    if (fileList.length === 0) {
      message.warning('请先选择JSON文件');
      return;
    }

    setGenerating(true);
    try {
      const generatedLicenses: {fileName: string, licenseData: any}[] = [];
      
      for (const file of fileList) {
        if (!file.originFileObj) continue;
        
        const fileContent = await readFileContent(file.originFileObj);
        const hardwareInfo = JSON.parse(fileContent);

        // 验证必要字段
        if (!hardwareInfo.cpu_id || !hardwareInfo.mac_address || !hardwareInfo.expiry_date) {
          message.error(`文件 ${file.name} 缺少必要信息`);
          continue;
        }

        // 生成License
        const response = await fetch('/api/license/generate', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            cpuId: hardwareInfo.cpu_id,
            cpuName: hardwareInfo.cpu_name,
            macAddress: hardwareInfo.mac_address,
            publicIp: hardwareInfo.public_ip || '',
            expiryDate: hardwareInfo.expiry_date,
            admin: hardwareInfo.admin || false
          })
        });

        const result = await response.json();
        
        if (result.status === 200) {
          generatedLicenses.push({
            fileName: file.name.replace('.json', '-license.json'),
            licenseData: result.data
          });
        } else {
          message.error(`生成 ${file.name} 的License失败: ${result.message}`);
        }
      }

      // 打包下载所有生成的License
      if (generatedLicenses.length > 0) {
        // 动态导入JSZip库
        const JSZip = (await import('jszip')).default;
        const zip = new JSZip();
        
        // 将每个License添加到zip文件中
        generatedLicenses.forEach(item => {
          zip.file(item.fileName, JSON.stringify(item.licenseData, null, 2));
        });
        
        // 生成zip文件并下载
        const content = await zip.generateAsync({ type: 'blob' });
        const url = URL.createObjectURL(content);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'batch-licenses.zip';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        message.success(`成功生成 ${generatedLicenses.length} 个License`);
      }
    } catch (error) {
      console.error('批量生成License失败:', error);
      message.error('批量生成License失败');
    } finally {
      setGenerating(false);
    }
  };

  const readFileContent = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = (e) => resolve(e.target?.result as string);
      reader.onerror = reject;
      reader.readAsText(file);
    });
  };

  return (
    <div style={{ maxWidth: 800, margin: '0 auto', padding: '24px' }}>
      <Card title="批量生成License">
        <Space direction="vertical" style={{ width: '100%' }} size="large">
          <Upload.Dragger
            multiple
            fileList={fileList}
            onChange={handleFileSelect}
            beforeUpload={() => false} // 阻止自动上传
            accept=".json,application/json"
          >
            <Button icon={<UploadOutlined />}>选择JSON文件</Button>
            <p style={{ marginTop: 16 }}>点击或拖拽JSON文件到此区域</p>
            <p>支持多文件选择</p>
          </Upload.Dragger>

          {/* {fileList.length > 0 && (
            <Card title="已选择文件" size="small">
              <List
                dataSource={fileList}
                renderItem={(file) => (
                  <List.Item>
                    <div>{file.name}</div>
                  </List.Item>
                )}
              />
            </Card>
          )} */}

          <div style={{ textAlign: 'center' }}>
            <Button
              type="primary"
              size="large"
              onClick={handleBatchGenerate}
              loading={generating}
              disabled={fileList.length === 0}
            >
              批量生成License
            </Button>
          </div>
        </Space>
      </Card>
    </div>
  );
}